 //
//  PhotoBaseManager.m
//  Filmax Pictures
//
//  Created by Jonas on 16/8/19.
//  Copyright © 2016年 Jonas. All rights reserved.
//

#import "PhotoBaseManager.h" 
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface PhotoBaseManager ()

@property (nonatomic, assign) BOOL compress;
@property (nonatomic, assign) BOOL edited;
@property (nonatomic, assign) NSInteger photoSize;
@property (nonatomic, assign) NSInteger photoWidth;

@end

static PhotoBaseManager * phtoGraph;
@implementation PhotoBaseManager

+ (PhotoBaseManager *)photoBaseShareManage{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        phtoGraph = [[PhotoBaseManager alloc] init];
    });
    
    return phtoGraph;
}


#pragma mark - 相机获取图片并图片保存
//拍摄照片
- (void)getPhotoPicture:(UIViewController *)viewController {
    if([PhotoBaseManager judgeTheRootOpenCamera]){
        
        UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
        imagePickController.delegate = self;
        imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [viewController presentViewController:imagePickController animated:YES completion:nil];
    } else {
        [PhotoBaseManager enterTheCameraFunction:viewController];
    }
}

#pragma mark - 图片浏览和删除功能
//只是图片浏览
- (void)tapBrowserNoDelete:(NSInteger)selectIndext imageMutableArray:(NSMutableArray *)imageMutableArray viewController:(UIViewController *)viewController {
    
    //图片浏览器
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc]init];
    //淡入淡出效果
    pickerBrowser.status = UIViewAnimationAnimationStatusFade;
    //是否可以有删除功能
    pickerBrowser.editing = NO;
    
//    pickerBrowser.delegate = self;
    
    //现有图片加入数组
    NSMutableArray *mutableArryI = [NSMutableArray array];
    
    for (int i = 0;i < imageMutableArray.count ; i++) {
        
        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc]init];
        if (imageMutableArray[i] == nil) {
            photo.thumbImage = [UIImage imageNamed:@"u68"];
            photo.thumbImage = [UIImage imageNamed:@"u68"];
        } else {
            photo.thumbImage = [UIImage imageWithData:imageMutableArray[i]];
            photo.photoImage = [UIImage imageWithData:imageMutableArray[i]];
        }
        
        [mutableArryI addObject:photo];
    }
    
    //    NSLog(@" 选择的第几个 %ld 存放照片的数组 %@",(long)selectIndext,[[DataBaseManager shareManager] getImageFromDocuments:imageMutableArray[0]]);
    
    pickerBrowser.photos = mutableArryI;
    //当前选中值
    pickerBrowser.currentIndex = selectIndext;
    //展开控制器
    [pickerBrowser showPickerVc:viewController];
    
}

//图片浏览删除
- (void)tapBrowser:(NSInteger)selectIndext imageMutableArray:(NSMutableArray *)imageMutableArray viewController:(UIViewController * )viewController{
    
    //图片浏览器
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc]init];
    //淡入淡出效果
    pickerBrowser.status = UIViewAnimationAnimationStatusFade;
    //是否可以有删除功能
    pickerBrowser.editing = YES;
    
    pickerBrowser.delegate = self;
    
    //现有图片加入数组
    NSMutableArray *mutableArryI = [NSMutableArray array];
    
    for (int i = 0;i < imageMutableArray.count ; i++) {
        
        ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc]init];
        if (imageMutableArray[i] == nil) {
            photo.thumbImage = [UIImage imageNamed:@"u68"];
            photo.thumbImage = [UIImage imageNamed:@"u68"];
        } else {
            photo.thumbImage = [UIImage imageWithData:imageMutableArray[i]];
            photo.photoImage = [UIImage imageWithData:imageMutableArray[i]];
        }
        
        [mutableArryI addObject:photo];
    }
    
//    NSLog(@" 选择的第几个 %ld 存放照片的数组 %@",(long)selectIndext,[[DataBaseManager shareManager] getImageFromDocuments:imageMutableArray[0]]);
    
    pickerBrowser.photos = mutableArryI;
    //当前选中值
    pickerBrowser.currentIndex = selectIndext;
    //展开控制器
    [pickerBrowser showPickerVc:viewController];
}

//删除照片
- (void)photoBrowser:(ZLPhotoPickerBrowserViewController *)photoBrowser removePhotoAtIndex:(NSInteger)index{
    _deletPicture(index);
}

#pragma mark - 相机获取图片并图片保存
//拍摄照片
- (void)getPhotoPicture:(UIViewController *)viewController compress:(BOOL)compress photoSize:(NSInteger)photoSize photoWidth:(NSInteger)photoWidth edited:(BOOL)edited photoBlock:(GetPhotoImage)photoBlock {
    _compress = compress;
    _edited = edited;
    _photoSize = photoSize;
    _photoWidth = photoWidth;
    if([PhotoBaseManager judgeTheRootOpenCamera]){
        _getPhotoImage = photoBlock;
        UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
        imagePickController.delegate = self;
        if (edited) {
            imagePickController.allowsEditing = YES;
        } else {
            imagePickController.allowsEditing = NO;
        }
        imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [viewController presentViewController:imagePickController animated:YES completion:nil];
    } else {
        [PhotoBaseManager enterTheCameraFunction:viewController];
    } 
}

//从相册获取
- (void)getPhotoPictureFromAlbum:(UIViewController *)viewController compress:(BOOL)compress photoSize:(NSInteger)photoSize photoWidth:(NSInteger)photoWidth edited:(BOOL)edited photoBlock:(GetPhotoImage)photoBlock {
    _compress = compress;
    _edited = edited;
    _photoSize = photoSize;
    _photoWidth = photoWidth;
    if ([PhotoBaseManager judgeTheRootOpenAlbum]) {
        _getPhotoImage = photoBlock;
        UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
        imagePickController.delegate = self;
        if (edited) {
            imagePickController.allowsEditing = YES;
        } else {
            imagePickController.allowsEditing = NO;
        }
        imagePickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        imagePickController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [viewController presentViewController:imagePickController animated:YES completion:nil];
    } else {
        [PhotoBaseManager enterTheAlbumFunction:viewController];
    }
}

//相机获取数据
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *imageNeed;
    
    if (_edited) {
        imageNeed = info[@"UIImagePickerControllerEditedImage"];
    } else {
        imageNeed = info[@"UIImagePickerControllerOriginalImage"];
    }
    
    NSData * imageData;
    
    if (_compress) {
        CGFloat scaleH = imageNeed.size.height * _photoWidth / imageNeed.size.width  ;
        UIImage *tmpImage = [[HelpObject manager] scaleFromImage:imageNeed toSize:CGSizeMake(_photoWidth, scaleH)];
//        imageData = [self compressImage:[HelpObject imageCompressForWidth:imageNeed targetWidth:_photoWidth] toMaxFileSize:_photoSize];
        imageData = [self compressImage:tmpImage toMaxFileSize:_photoSize];
    } else {
        imageData = UIImageJPEGRepresentation(imageNeed, 1);
    }
    
    self.getPhotoImage(imageData);
}

//图片压缩大小
- (NSData *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length]/1024 > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
//    NSLog(@"%ld",imageData.length/1024);
    return imageData;
//    UIImage *compressedImage = [UIImage imageWithData:imageData];
//    return compressedImage;
}

#pragma mark - 判断是否开启拍照权限问题
//没有权限时跳入照片服务开启功能
+ (void)openCameraFunction{
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
}
//判断是否有权利进行拍照
+ (BOOL)judgeTheRootOpenCamera{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        //无权限
        return NO;
    }
    return YES;
}

//判断是否有相册权限
+ (BOOL)judgeTheRootOpenAlbum {
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author ==kCLAuthorizationStatusRestricted || author ==kCLAuthorizationStatusDenied){
        //无权限
        return NO;
    }
    return YES;
}

//前往开启相册权限
+ (void)openAlbumFunction {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    }
    
}

//提示拍照权限
+ (void)enterTheCameraFunction:(UIViewController *)viewController{
    UIAlertController * alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先打开拍照权限设置 -> 隐私 -> 相机 -> app" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak __typeof(self) weakSelf = self;
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
//        [strongSelf openCameraFunction];
    }];
    [alterController addAction:action];
    [viewController presentViewController:alterController animated:YES completion:nil];
}

//提示相册权限
+ (void)enterTheAlbumFunction:(UIViewController *)viewController {
    UIAlertController * alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先打开相册权限设置 -> 隐私 -> 相册 -> app" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak __typeof(self) weakSelf = self;
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
//        [strongSelf openAlbumFunction];
    }];
    
    [alterController addAction:action];
    [viewController presentViewController:alterController animated:YES completion:nil];
    
}

//提示定位权限
+ (void)enterTheAddressFunction:(UIViewController *)viewController {
    UIAlertController * alterController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先打开定位权限设置 -> 隐私 -> 定位 -> app" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak __typeof(self) weakSelf = self;
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        //        [strongSelf openAlbumFunction];
    }];
    [alterController addAction:action];
    [viewController presentViewController:alterController animated:YES completion:nil];
    
}

@end
